package org.jslaughter.component.effect;

import org.jslaughter.event.eventtype.DamageEvent;
import org.jslaughter.event.eventtype.DamageEvent.DAMAGE_TYPE;
import org.jslaughter.event.eventtype.DamageListener;
import org.newdawn.slick.geom.Vector2f;
import org.nvframe.component.AbstractComponent;
import org.nvframe.component.state.Position;
import org.nvframe.entity.Entity;
import org.nvframe.event.EventService;
import org.nvframe.exception.NVFrameException;
import org.nvframe.factory.EntityFactory;
import org.nvframe.util.settings.SettingsObj;

/**
 * 
 * @author Nik Van Looy
 */
public class BloodOnDamage extends AbstractComponent implements DamageListener {
	
	private String bloodEntity;

	public BloodOnDamage(String id, Entity owner, SettingsObj settings) {
		super(id, owner);
		
		bloodEntity = settings.getString("bloodEntity");
		
		EventService.getInstance().addEventListener(this);
	}
	
	@Override
	public void damageReceived(DamageEvent event) {
		if(event.getTarget() != owner) 
			return;
		
		try {
			Entity entBlood = EntityFactory.getInstance().getEntityFromPrototype(bloodEntity);
			Position position = (Position) owner.getComponent(Position.class);
			Position bloodPosition = (Position) entBlood.getComponent(Position.class);
			
			// give the blood an offset when damage is done by a bullet
			if(event.getType() == DAMAGE_TYPE.BULLET) {
				Vector2f offsetPos = new Vector2f();
				float radDirection = (float) Math.toRadians(event.getTargetDirection());
				float offset = 20;

				offsetPos.set(position.getX() + (float) Math.cos(radDirection) * offset, 
						position.getY() + (float) Math.sin(radDirection) * offset);
				
				bloodPosition.setXY(offsetPos);
			}
			else
				bloodPosition.setXY(position.getXY());
			
			//bloodPosition.setDirection((Math.round(Math.random() * 359) + 1));
		} catch (NVFrameException e) {
			e.printStackTrace();
		}
	}

}
